<?php
/**
 * Note: *
 */

namespace App\Services\Wechat;

use EasyWeChat\OfficialAccount\Application as OfficialAccount;
use Illuminate\Support\Facades\Cache;
use Overtrue\LaravelWeChat\Facade as EasyWeChat;

class OfficialAccountService
{
    protected const CACHE_TAG = 'official_account';

    /**
     * @var OfficialAccount
     */
    protected $app;

    public function getInstance()
    {
        if ($this->app) return $this->app;
        $this->app = EasyWeChat::officialAccount();
        return $this->app;
    }

    /**
     * 获取用户信息
     * @param $openid
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function getUser($openid)
    {
        return $this->getInstance()->user->get($openid);
    }

    /**
     * 生成临时二维码
     * 将二维码数据存在缓存中, 避开场景值ID长度限制
     * @param int $event
     * @param $eventStr
     * @param int $ttl
     * @return string
     * @throws \Exception
     */
    public function getQrcodeTemporary(int $event, $eventStr, int $ttl = 600): string
    {
        $result = $this->getInstance()->qrcode->temporary($event, $ttl);
        $ticket = $result['ticket'];
        Cache::tags(self::CACHE_TAG)->set("ticket:{$ticket}", $eventStr, $ttl);
        return $this->getInstance()->qrcode->url($ticket);
    }

    /**
     * 根据 ticket 获取二维码信息
     * @param string $ticket
     * @return array|mixed
     */
    public function getQrcodeInfo(string $ticket)
    {
        return Cache::tags(self::CACHE_TAG)->get("ticket:{$ticket}", $ticket);
    }
}
